package com.tanhua.server.service;


import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.api.UserLocationApi;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.dubbo.server.vo.UserLocationVo;
import com.tanhua.server.enums.SexEnum;
import com.tanhua.server.pojo.Question;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.NearUserVo;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.sql.Ref;
import java.util.*;


@Service
public class TodayBestService {

    @Autowired
    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Autowired
    private UserService userService;

    @Autowired
    private RecommendUserService recommendUserService;

    @Autowired
    private UserInfoService userInfoService;

    @Value("${tanhua.sso.default.user}")
    private Long defaultUser;

    @Value("${tanhua.sso.default.recommend.users}")
    private String recommendUsers;

    @Autowired
    private QuestionService questionService;

    @Value("${tanhua.sso.url}")
    private String ssoUrl;

    @Autowired
    private RestTemplate restTemplate;

    @Reference(version = "1.0.0")
    private UserLocationApi userLocationApi;

    @Reference(version = "1.0.0")
    private UserLikeApi userLikeApi;

    @Autowired
    private IMService imService;

    /**
     * 查询今日佳人
     *
     * @return
     */
    public TodayBest queryTodayBest() {
        //根据登入用户的token查询用户信息
        User user = UserThreadLocal.get();

        //不为空
        //根据用户信息查询匹配的今日佳人
        TodayBest todayBest = recommendUserService.queryTodayBest(user.getId());
        if (null == todayBest) {
            // 默认推荐用户
            todayBest = new TodayBest();
            todayBest.setId(defaultUser);
        }

        //再根据佳人id,查询数据库补全对应的佳人信息
        UserInfo userInfo = userInfoService.queryById(todayBest.getId());
        //补全信息
        todayBest.setAge(userInfo.getAge());
        todayBest.setGender(userInfo.getSex().toString());
        todayBest.setNickname(userInfo.getNickName());
        todayBest.setAvatar(userInfo.getLogo());
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ","));

        return todayBest;
    }


    /**
     * 查询今日佳人详情
     *
     * @param userId 佳人id
     * @return
     */
    public TodayBest queryTodayBest(Long userId) {
        //获取当前登入用户信息
        User user = UserThreadLocal.get();
        //创建todayBest对象
        TodayBest todayBest = new TodayBest();
        //查询数据库,补全信息
        UserInfo userInfo = userInfoService.queryById(userId);
        todayBest.setId(userId); //佳人id
        todayBest.setAge(userInfo.getAge());  //年龄
        todayBest.setAvatar(userInfo.getLogo()); //头像
        todayBest.setGender(userInfo.getSex().name().toLowerCase()); //性别
        todayBest.setNickname(userInfo.getNickName()); //名称
        todayBest.setTags(StringUtils.split(userInfo.getTags(), ',')); //标签

        double score = recommendUserService.queryScore(userId, user.getId());
        if (score == 0) {
            //默认分组
            score = 98;
        }

        //缘分值
        todayBest.setFateValue(Double.valueOf(score).longValue());

        return todayBest;
    }


    /**
     * 获取推荐列表
     *
     * @param queryParam 前端传入的参数
     * @return
     */
    public PageResult queryRecommendUserList(RecommendUserQueryParam queryParam) {

        //根据用户的token查询用户信息
        User user = UserThreadLocal.get();

        //不为空
        //根据用户id查询到推荐用户的伪对象（这个对象里封装的是id及缘分值等，并不是真正的用户信息）
        PageInfo<RecommendUser> pageInfo = recommendUserService.queryRecommendUserList(user.getId(), queryParam.getPage(), queryParam.getPagesize());

        List<RecommendUser> records = pageInfo.getRecords();

        //如果未查询到,需要使用默认的推荐列表
        if (CollectionUtils.isEmpty(records)) {
            String[] ss = StringUtils.split(recommendUsers, ",");

            for (String s : ss) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(s));
                recommendUser.setToUserId(user.getId());
                recommendUser.setScore(RandomUtils.nextDouble(70, 98));

                records.add(recommendUser);

            }

        }


        //拿到用户匹配的所有佳人的id并封装到一个新的集合中
        //创建集合接受佳人ID
        List<Long> longList = new ArrayList<>();
        //遍历集合
        for (RecommendUser record : records) {
            //添加id到longList集合
            longList.add(record.getUserId());
        }

        //需要查询用户信息,并且按照条件查询
        //创建查询条件
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.in("user_id", longList);   //用户id


   /*     if (queryParam.getAge() != null) {
            wrapper.lt("age", queryParam.getAge());   //年龄
        }

        if (StringUtils.isNotEmpty(queryParam.getCity())) {
            wrapper.eq("city", queryParam.getCity());  //城市
        }
*/
        //根据推荐用户id查询数据库获取推荐用户信息
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(wrapper);

        //创建todayBest集合接收推荐列表
        List<TodayBest> todayBestList = new ArrayList<>();

        //遍历userInfoList
        for (UserInfo userInfo : userInfoList) {
            TodayBest todayBest = new TodayBest();
            //补全信息
            todayBest.setId(userInfo.getUserId());
            todayBest.setAge(userInfo.getAge());
            todayBest.setGender(userInfo.getSex().toString());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ","));

            //设置缘分值
            for (RecommendUser record : records) {
                //如果返回的佳人对象中的id和推荐用户的id相等则将缘分值封装进佳人对象中
                if (userInfo.getUserId().longValue() == record.getUserId().longValue()) {
                    double score = Math.floor(record.getScore());
                    todayBest.setFateValue(Double.valueOf(score).longValue());
                    break;
                }
            }
            todayBestList.add(todayBest);
        }

        //再根据缘分值进行倒叙排序
        Collections.sort(todayBestList, new Comparator<TodayBest>() {
            @Override
            public int compare(TodayBest o1, TodayBest o2) {
                return o2.getFateValue().compareTo(o1.getFateValue());
            }
        });

        //创建返回的PageResult对象
        PageResult pageResult = new PageResult();
        pageResult.setPage(queryParam.getPage());
        pageResult.setPagesize(queryParam.getPagesize());
        pageResult.setItems(todayBestList);

        //返回结果参数给前端
        return pageResult;
    }


    /**
     * 查询陌生人问题
     *
     * @param userId 陌生人的id
     * @return
     */
    public String queryQuestion(Long userId) {
        Question question = questionService.queryQuestion(userId);
        if (question != null) {
            return question.getTxt();
        }
        return "";
    }

    /**
     * 回复陌生人问题，发送消息给对方
     *
     * @param userId
     * @param reply
     * @return
     */
    public Boolean replyQuestion(Long userId, String reply) {
        //获取user信息
        User user = UserThreadLocal.get();
        //查询数据库获取用户信息
        UserInfo userInfo = userInfoService.queryById(user.getId());

        //构建消息内容
        Map<String, Object> msg = new HashMap<>();
        msg.put("userId", user.getId().toString());
        msg.put("nickname", queryQuestion(userId));  //消息名称
        msg.put("strangerQuestion", userInfo.getNickName()); //问题
        msg.put("reply", reply); //回答

        try {
            //将消息内容转换成json格式
            String msgStr = MAPPER.writeValueAsString(msg);

            String url = ssoUrl + "/user/huanxin/messages";

            //请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);  //提交类型

            //请求体
            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
            params.add("target", userId.toString());
            params.add("msg", msgStr);


            HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity(params, headers);

            ResponseEntity<Void> responseEntity = restTemplate.postForEntity(url, httpEntity, Void.class);

            return responseEntity.getStatusCodeValue() == 200;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return false;
    }


    /**
     * 搜附近
     *
     * @param gender   性别
     * @param distance 距离
     * @return
     */
    public List<NearUserVo> queryNearUser(String gender, String distance) {
        //获取当前用户信息
        User user = UserThreadLocal.get();
        //查询当前用户的位置信息
        UserLocationVo userLocationVo = userLocationApi.queryByUserId(user.getId());
        Double longitude = userLocationVo.getLongitude();  //经度
        Double latitude = userLocationVo.getLatitude();  //纬度

        //根据当前用户的位置查询附近好友
        List<UserLocationVo> userLocationVoList = userLocationApi.queryUserFromLocation(longitude, latitude, Integer.valueOf(distance));

        //非空处理
        if (CollectionUtils.isEmpty(userLocationVoList)) {
            return Collections.emptyList();   //返回一个空集合
        }

        //创建用户id集合
        List<Long> userIds = new ArrayList<>();
        for (UserLocationVo locationVo : userLocationVoList) {
            userIds.add(locationVo.getUserId());
        }

        //构建搜索条件(性别和距离)
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.in("user_id", userIds);
        if (StringUtils.equalsIgnoreCase(gender, "man")) {
            queryWrapper.eq("sex", SexEnum.MAN);
        } else if (StringUtils.equalsIgnoreCase(gender, "woman")) {
            queryWrapper.eq("sex", SexEnum.WOMAN);
        }

        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(queryWrapper);

        //创建NearUserVo对象集合封装NearUserVo
        List<NearUserVo> nearUserVoList = new ArrayList<>();


        for (UserLocationVo locationVo : userLocationVoList) {

            //排除自己
            if (locationVo.getUserId().longValue() == user.getId().longValue()) {
                continue;  //跳过
            }

            //封装信息
            for (UserInfo userInfo : userInfoList) {
                if (locationVo.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    NearUserVo nearUserVo = new NearUserVo();
                    nearUserVo.setAvatar(userInfo.getLogo());
                    nearUserVo.setNickname(userInfo.getNickName());
                    nearUserVo.setUserId(userInfo.getUserId());

                    nearUserVoList.add(nearUserVo);
                    break;

                }
            }
        }
        return nearUserVoList;
    }


    /**
     * 探花卡片展示
     *
     * @return
     */
    public List<TodayBest> queryCardsList() {
        //获取用户信息
        User user = UserThreadLocal.get();
        //查询推荐的用户
        PageInfo<RecommendUser> pageInfo = recommendUserService.queryRecommendUserList(user.getId(), 1, 50);
        //如果获取的推荐用户为空.则推荐默认列表
        if (CollectionUtils.isEmpty(pageInfo.getRecords())) {
            String[] split = StringUtils.split(recommendUsers, ",");
            for (String s : split) {
                RecommendUser recommendUser = new RecommendUser();
                recommendUser.setUserId(Long.valueOf(s));  //推荐用户id
                recommendUser.setToUserId(user.getId());  //用户id
                pageInfo.getRecords().add(recommendUser);
            }
        }

        List<RecommendUser> records = pageInfo.getRecords();
        //定义范围
        int showCount = Math.min(10, records.size());

        List<RecommendUser> newRecords = new ArrayList<>();
        for (int i = 0; i < showCount; i++) {
            //随机选出推荐的好友
            createRecommendUser(newRecords, records);
        }


        //获取推荐好友的id集合
        List<Long> userIds = new ArrayList<>();
        for (RecommendUser record : newRecords) {
            userIds.add(record.getUserId());
        }

        //创建查询数据库条件
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("user_id", userIds);
        //查询数据库
        List<UserInfo> userInfoList = userInfoService.queryUserInfoList(queryWrapper);
        //创建todaybeat对象
        List<TodayBest> todayBestList = new ArrayList<>();
        //封装对象
        for (UserInfo userInfo : userInfoList) {
            TodayBest todayBest = new TodayBest();
            todayBest.setGender(userInfo.getSex().toString());
            todayBest.setId(userInfo.getUserId());
            todayBest.setAge(userInfo.getAge());
            todayBest.setAvatar(userInfo.getLogo());
            todayBest.setNickname(userInfo.getNickName());
            todayBest.setTags(StringUtils.split(userInfo.getTags(), ','));
//            todayBest.setFateValue(0L);


            todayBestList.add(todayBest);

        }
        return todayBestList;
    }


    /**
     * 递归随机生产推荐好友,保证不重复
     */
    private void createRecommendUser(List<RecommendUser> newRecords, List<RecommendUser> records) {

        RecommendUser recommendUser = records.get(RandomUtils.nextInt(0, records.size() - 1));
        if (!newRecords.contains(recommendUser)) {
            newRecords.add(recommendUser);
        } else {
            //开始递归
            createRecommendUser(newRecords, records);
        }

    }


    /**
     *  喜欢
     * @param likeUserId
     */
    public Boolean likeUser(Long likeUserId) {
        //获取当前用户信息
        User user = UserThreadLocal.get();
        //添加到喜欢的列表中
        String s = userLikeApi.saveUserLike(user.getId(), likeUserId);
        if (StringUtils.isEmpty(s)){
            return false;
        }

        //查询是否互相喜欢 ,如果互相喜欢就添加为好友
        if (this.userLikeApi.isMutualLike(user.getId(), likeUserId)) {
            //相互喜欢成为好友
            this.imService.contactUser(likeUserId);
        }

        return true;

    }

    /**
     *  不喜欢
     * @param likeUserId
     * @return
     */
    public Boolean disLikeUser(Long likeUserId) {
        User user = UserThreadLocal.get();
        return this.userLikeApi.deleteUserLike(user.getId(), likeUserId);
    }
}
